<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, View, Delete } from '@element-plus/icons-vue';
import BedModal from './components/BedModal.vue';
import { fetchBedList, fetchBedStats, fetchBedDetail, deleteBed } from '@/api/bed';

// --- Reactive State ---
const bedList = ref([]);
const total = ref(0);
const page = ref(1);
const size = ref(10);
const filters = ref({
  roomNumber: '',
  status: '',
});
const loading = ref(true);

const stats = ref({
  totalBeds: 0,
  occupiedBeds: 0,
  vacantBeds: 0,
  occupancyRate: 0,
});

// Modal control
const showModal = ref(false);
const modalMode = ref('add');
const currentBedId = ref(null);

// --- API Functions ---
const getBedData = async () => {
  loading.value = true;
  try {
    const params = {
      page: page.value,
      size: size.value,
      roomNumber: filters.value.roomNumber || undefined,
      status: filters.value.status || undefined,
    };
    const res = await fetchBedList(params);
    bedList.value = res.list;
    total.value = res.total;
  } catch (error) {
    ElMessage.error('获取床位列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const getBedStats = async () => {
  try {
    const res = await fetchBedStats();
    // Format occupancyRate to 2 decimal places if it's not an integer
    res.occupancyRate = parseFloat(res.occupancyRate.toFixed(2));
    stats.value = res;
  } catch (error) {
    ElMessage.error('获取床位统计失败');
    console.error(error);
  }
};

// --- Event Handlers ---
const handleFilter = () => {
  page.value = 1;
  getBedData();
};

const handleResetFilters = () => {
  filters.value.roomNumber = '';
  filters.value.status = '';
  handleFilter();
};

const handleDelete = (id) => {
  ElMessageBox.confirm('您确定要删除此床位吗？此操作不可逆！', '危险操作', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteBed(id);
      ElMessage.success('删除成功');
      // Refresh both list and stats
      getBedData();
      getBedStats();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  }).catch(() => { });
};

const openAddModal = () => {
  modalMode.value = 'add';
  currentBedId.value = null;
  showModal.value = true;
};

const openViewModal = (id) => {
  modalMode.value = 'view';
  currentBedId.value = id;
  showModal.value = true;
};

const handleModalClose = (refresh) => {
  showModal.value = false;
  if (refresh) {
    getBedData();
    getBedStats();
  }
};

// --- Pagination Handlers ---
const handleSizeChange = (newPageSize) => {
  size.value = newPageSize;
  page.value = 1; // Reset to first page
  getBedData();
};

const handleCurrentChange = (newPage) => {
  page.value = newPage;
  getBedData();
};

// --- Lifecycle Hook ---
onMounted(() => {
  getBedData();
  getBedStats();
});
</script>

<template>
  <div class="page-container">
    <h1 class="page-title">床位管理中心</h1>

    <div class="stats-grid">
      <div class="stat-card card-total">
        <div class="stat-icon-wrapper"><i class="fa-solid fa-bed"></i></div>
        <div class="stat-content">
          <p class="stat-title">总床位数</p>
          <p class="stat-value">{{ stats.totalBeds }}</p>
        </div>
      </div>
      <div class="stat-card card-occupied">
        <div class="stat-icon-wrapper"><i class="fa-solid fa-person-shelter"></i></div>
        <div class="stat-content">
          <p class="stat-title">占用床位数</p>
          <p class="stat-value">{{ stats.occupiedBeds }}</p>
        </div>
      </div>
      <div class="stat-card card-vacant">
        <div class="stat-icon-wrapper"><i class="fa-solid fa-door-open"></i></div>
        <div class="stat-content">
          <p class="stat-title">空闲床位数</p>
          <p class="stat-value">{{ stats.vacantBeds }}</p>
        </div>
      </div>
      <div class="stat-card card-rate">
        <div class="stat-icon-wrapper"><i class="fa-solid fa-percent"></i></div>
        <div class="stat-content">
          <p class="stat-title">入住率</p>
          <p class="stat-value">{{ stats.occupancyRate }}%</p>
        </div>
      </div>
    </div>

    <div class="content-card">
      <div class="operation-bar">
        <div class="filters">
          <el-input v-model="filters.roomNumber" placeholder="按房间号搜索" clearable @keyup.enter="handleFilter" />
          <el-select v-model="filters.status" placeholder="选择状态" clearable>
            <el-option label="空闲" value="VACANT" />
            <el-option label="占用" value="OCCUPIED" />
          </el-select>
          <el-button type="primary" :icon="Search" @click="handleFilter">筛选</el-button>
          <el-button @click="handleResetFilters">重置</el-button>
        </div>
        <el-button type="success" :icon="Plus" @click="openAddModal">新增床位</el-button>
      </div>

      <el-table :data="bedList" v-loading="loading" class="bed-table">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="roomNumber" label="房间号" width="120" />
        <el-table-column prop="bedNumber" label="床位号" width="120" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'VACANT' ? 'success' : 'warning'" effect="light" round>
              <i :class="row.status === 'VACANT' ? 'fa-solid fa-circle-check' : 'fa-solid fa-circle-xmark'" style="margin-right: 4px;"></i>
              {{ row.status === 'VACANT' ? '空闲' : '占用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="costPerMonth" label="月费用(元)" width="120">
            <template #default="{ row }">
                ¥ {{ row.costPerMonth.toFixed(2) }}
            </template>
        </el-table-column>
        <el-table-column prop="occupiedByUserId" label="占用用户ID" width="120" align="center" />
        <el-table-column prop="notes" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="View" @click="openViewModal(row.id)">查看</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <BedModal
      v-if="showModal"
      :mode="modalMode"
      :bed-id="currentBedId"
      @close="handleModalClose"
    />
  </div>
</template>

<style lang="scss" scoped>
// Using Font Awesome for icons, make sure to include it in your project!
// e.g., in your index.html: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

.page-container {
  width: 99%;
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  color: white;
  overflow: hidden;
  position: relative;
  transition: transform 0.3s ease, box-shadow 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
  }

  .stat-icon-wrapper {
    font-size: 36px;
    opacity: 0.8;
    margin-right: 20px;
  }
  
  .stat-content {
    .stat-title {
      font-size: 14px;
      margin: 0 0 8px 0;
      opacity: 0.9;
    }
    .stat-value {
      font-size: 30px;
      font-weight: 700;
      margin: 0;
    }
  }

  &.card-total { background: linear-gradient(135deg, #409eff, #79bbff); }
  &.card-occupied { background: linear-gradient(135deg, #e6a23c, #f3d19e);  }
  &.card-vacant { background: linear-gradient(135deg, #67c23a, #95d475);}
  &.card-rate { background: linear-gradient(135deg, #909399, #b1b3b8); }
}

.content-card {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .filters {
    display: flex;
    gap: 16px;
    
    .el-input, .el-select {
      width: 180px;
    }
  }
}

.bed-table {
  width: 100%;
  border-radius: 8px;
  :deep(th) {
    background-color: #fafafa !important;
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}
</style>